package cn.south.campus.common.utils;

import org.springframework.util.StringUtils;

/**
 * <p>
 *
 * </p>
 *
 * @author chow
 * @since 2023/3/16 17:35
 */
public class FileUtils {
    /**
     * 字符常量：斜杠 {@code '/'}
     */
    private static final char SLASH = '/';

    /**
     * 字符常量：反斜杠 {@code '\\'}
     */
    private static final char BACKSLASH = '\\';

    private static final String IMAGE_PNG = "image/png";

    private static final String IMAGE_JPG = "image/jpg";

    private static final String IMAGE_JPEG = "image/jpeg";

    private static final String IMAGE_BMP = "image/bmp";

    private static final String IMAGE_GIF = "image/gif";

    /**
     * 返回文件名
     *
     * @param filePath 文件
     * @return 文件名
     */
    public static String getName(String filePath) {
        if (null == filePath) {
            return null;
        }
        int len = filePath.length();
        if (0 == len) {
            return filePath;
        }
        if (isFileSeparator(filePath.charAt(len - 1))) {
            // 以分隔符结尾的去掉结尾分隔符
            len--;
        }

        int begin = 0;
        char c;
        for (int i = len - 1; i > -1; i--) {
            c = filePath.charAt(i);
            if (isFileSeparator(c)) {
                // 查找最后一个路径分隔符（/或者\）
                begin = i + 1;
                break;
            }
        }

        return filePath.substring(begin, len);
    }

    public static String getExtension(String originalFilename, String contentType) {
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (StringUtils.hasLength(fileExtension) && StringUtils.hasLength(contentType)) {
            switch (contentType) {
                case IMAGE_PNG:
                    return "png";
                case IMAGE_JPG:
                    return "jpg";
                case IMAGE_JPEG:
                    return "jpeg";
                case IMAGE_BMP:
                    return "bmp";
                case IMAGE_GIF:
                    return "gif";
                default:
                    return null;
            }
        }
        return fileExtension;
    }


    /**
     * 是否为Windows或者Linux（Unix）文件分隔符<br>
     * Windows平台下分隔符为\，Linux（Unix）为/
     *
     * @param c 字符
     * @return 是否为Windows或者Linux（Unix）文件分隔符
     */
    private static boolean isFileSeparator(char c) {
        return SLASH == c || BACKSLASH == c;
    }
}
